import AesUtils from './aes-utils'
import RsaUtils from './rsa-utils'
/**
 * 随机字符串
 * @param num
 * @returns {string}
 */
function randomStr(num) {
  if (!num) {
    num = 0
  }
  let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
  let nums = "";
  for (let i = 0; i < num; i++) {
    let id = parseInt((Math.random() * 61).toString());
    nums += chars[id];
  }
  return nums;
}

/**
 * 随机密钥对
 */
function randomKey() {
  let result = {
    key: randomStr(16),
    iv: randomStr(16)
  }
  result.text = result.key + "," + result.iv
  return result;
}



/**
 * 构建参数
 * @param prams
 * @returns
 */
export default function buildParams(prams){
  if(typeof prams !== "object"){
    console.log("必须要object对象的参数才能进行buildParams！")
    return false
  }
  // 时间戳
  prams['timestamp'] = new Date().getTime()/1000
  // 随机密码对
  let keyObj = randomKey();
  // 发布时去掉此处
  console.log('准备加密参数：',prams)
  console.log('加密key:',keyObj)
  console.log('明文数据：',JSON.stringify(prams))
  // aes加密数据
  const aesEncrypt = AesUtils.encrypt(JSON.stringify(prams),keyObj.key,keyObj.iv);
  console.log('加密结果:',aesEncrypt)
  // key和iv
  const keyIv = RsaUtils.encrypt(keyObj.text);
  return {
    data:aesEncrypt,
    key:keyIv
  }
}
export default {
  buildParams
}
